package com.fudan.gamestore.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ArrayListTypeHandler<T> extends BaseTypeHandler<List<T>> {
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private Class<List<T>> clazz;

    public ArrayListTypeHandler(Class<List<T>> clazz) {
        if(clazz == null){
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.clazz=clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i,toJson(parameter));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
//特别要注意在转集合的情况下，第二个参数是List.class,而不是clazz会报奇怪的错误，我在这被坑了老久
        return toObject(rs.getString(columnName));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return toObject(rs.getString(columnIndex));
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return toObject(cs.getString(columnIndex));
    }

    private String toJson(List<T> object) {
        try {
            return MAPPER.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private List<T> toObject(String content) {
        if (content != null && !content.isEmpty()) {
            try {
                return (List<T>) MAPPER.readValue(content, (Class<?>) List.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            return null;
        }
    }
}